package com.app.sv.ywms.ck

import com.app.exception.BusinessException
import com.app.pub.billtype.PubBilltype
import com.app.ywms.ck.zmtd.Yzmtdb
import com.app.ywms.ck.zmtd.Yzmtdh
import com.app.ywms.kc.Ycrkmx

class YzmtdService {
    def pubActionscriptService
    def billGenNoService
    def springSecurityService
    static  transactional = true
    def save(Yzmtdh head, bodys){


        if(bodys==null || bodys.size()==0)
            throw new BusinessException('表体数据不能为空!')
        if(!head.isAttached()){//如果是新单据 添加单据号
            def billtype =PubBilltype.findByBilltypecode(head.billTypeCode)
            def no=billGenNoService.getNo(billtype, head.bdCorp);
            head.billno=no

            //设置单据类型
            head.billtype = billtype
        }

        pubActionscriptService.runScript('YZMTD','save',[data: head],0,null)
        //删除原有的表体
        head?.bodys?.each {
            def rk=it.rk
            rk.hxsl=rk.hxsl-it.bcsy
            rk.save()
            head.removeFromBodys(it)
            it.delete()
        }

        bodys.each{
            it.head=head
            it.save()

            it.rk.hxsl=it.rk.hxsl+it.bcsy
            it.rk.save()
        }
        head.save()
        //回写 数据


//        head.fbillFlag=BillState._FREE           //设置单据为自由态






        def data = pubActionscriptService.runScript('YZMTD','save',[data: head],1,null)
        return data
    }
    def delete(String id){
        def head = Yzmtdh.get(id)
        if (!head) {
            throw new BusinessException('未找到要删除的数据!')
        }
        if(head.checker!=null){
            throw new BusinessException('单据已经是审核状态,不能删除！')
        }

        head?.bodys?.each {
            def rk=it.rk
            rk.hxsl=rk.hxsl-it.bcsy
            rk.save()

        }
        head.delete()
        pubActionscriptService.runScript('YXHJHD','delete',[data:yxhjhdInstance],1,null)
    }


    def check(String id){
       def head= Yzmtdh.get(id)

        if(head.checker)
            throw  new BusinessException('单据已经审核！')
        head.checker=springSecurityService.currentUser
        head.checkDate=new Date()
        head.save()
    }

    def uncheck(String id){
        def head=Yzmtdh.get(id)
        if(!head.checker)
            throw new BusinessException('单据未审核！')
        head.checkDate=null
        head.checker=null
        head.save()
    }



}
